package top.shiyiri.service.impl;

import top.shiyiri.dao.BookDao;
import top.shiyiri.dao.impl.BookDaoImpl;
import top.shiyiri.pojo.Book;
import top.shiyiri.pojo.Page;
import top.shiyiri.service.BookService;

import java.util.List;

/**
 * @author Aunean
 * @date 2022/2/8 11:00
 */
public class BookServiceImpl implements BookService {

    private BookDao dao = new BookDaoImpl();
    @Override
    public void addBook(Book book) {
        dao.addBook(book);
    }

    @Override
    public void deleteBookById(Integer id) {
        dao.deleteBook(id);
    }

    @Override
    public void updateBook(Book book) {
        dao.updateBook(book);
    }

    @Override
    public Book queryBookById(Integer id) {
        return dao.queryBookById(id);
    }

    @Override
    public List<Book> queryBooks() {
        return dao.queryBooks();
    }

    @Override
    public Page<Book> page(int pageNo, int pageSize) {
        Page<Book> page = new Page<>();

        page.setPageSize(pageSize); //设置每页显示数量

        //求总记录数
        int pageTotalCount = dao.queryForPageTotalCount();
        page.setPageTotalCount(pageTotalCount); //设置总记录数

        //求总页码
        Integer pageTotal = pageTotalCount % pageSize == 0? pageTotalCount / pageSize: pageTotalCount / pageSize + 1;
        page.setPageTotal(pageTotal);//设置总页码

        /*
        数据编码的有效检查
         */
        if (pageNo < 1) {
            pageNo = 1;
        }
        if (pageNo > pageTotal) {
            pageNo = pageTotal;
        }
        page.setPageNo(pageNo); //设置当前页码
        //求当前页数据的开始索引
        int begin = (pageNo - 1) * pageSize;

        //求当前页数据
        List<Book> items = dao.queryForPageItems(begin, pageSize);
        //设置当前页数据
        page.setItems(items);
        return page;
    }

    @Override
    public Page<Book> pageByPrice(int pageNo, int pageSize, int min, int max) {
        Page<Book> page = new Page<>();

        page.setPageSize(pageSize); //设置每页显示数量

        //求总记录数
        int pageTotalCount = dao.queryForPageTotalCountByPrice(min, max);
        page.setPageTotalCount(pageTotalCount); //设置总记录数

        //求总页码
        Integer pageTotal = pageTotalCount % pageSize == 0? pageTotalCount / pageSize: pageTotalCount / pageSize + 1;
        page.setPageTotal(pageTotal);//设置总页码

        /*
        数据编码的有效检查
         */
        if (pageNo < 1) {
            pageNo = 1;
        }
        if (pageNo > pageTotal) {
            pageNo = pageTotal;
        }
        page.setPageNo(pageNo); //设置当前页码
        //求当前页数据的开始索引
        int begin = (pageNo - 1) * pageSize;

        //求当前页数据
        List<Book> items = dao.queryForPageItemsByPrice(begin, pageSize, min, max);
        //设置当前页数据
        page.setItems(items);
        return page;
    }
}
